package com.bailian.service;

import com.alibaba.fastjson.JSONObject;
import com.bailian.constant.Constants;
import com.bailian.core.utils.BeanCopyUtils;
import com.bailian.core.utils.MD5Util;
import com.bailian.core.utils.RedisUtil;
import com.bailian.feign.VerificaCodeFeign;
import com.bailian.mapper.UserMapper;
import com.bailian.mapper.entity.UserDo;
import com.bailian.member.IMemberRegisterService;
import com.bailian.member.dto.input.UserInpDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * ClassName: MemberRegisterService <br/>
 * Description: <br/>
 * date: 2019/9/5 23:53<br/>
 *
 * @author XT<br />
 */
@RestController
public class MemberRegisterService extends BaseApiService<JSONObject> implements IMemberRegisterService {

    @Autowired
    private VerificaCodeFeign verificaCodeFeign;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Transactional
    public BaseResponse<JSONObject> register(@RequestBody @Validated UserInpDTO userInpDTO, String registCode) {
        final UserDo user = userMapper.existMobile(userInpDTO.getMobile());
        if (user != null) return setResultError("此号码已注册");
        BaseResponse<JSONObject> response = verificaCodeFeign.verifyWeixinCode(userInpDTO.getMobile(), registCode);
        Integer code = response.getRtnCode();
        if (code != 200) {
            return setResultError(response.getMsg());
        }
        String password = MD5Util.MD5(userInpDTO.getPassword());
        userInpDTO.setPassword(password);
        UserDo userDo = BeanCopyUtils.dtoToDo(userInpDTO, UserDo.class);
        int rt = userMapper.register(userDo);
        if (rt > 0) redisUtil.delKey(Constants.WEIXINCODE_KEY + userInpDTO.getMobile());
        return rt > 0 ? setResultSuccess("注册成功") : setResultSuccess("注册失败");
    }

}
